// pages/goods/goodsDetail/goodsDetail.js
const common = require('../../../utils/util.js')
const app = getApp()
Page({

    /**
     * 页面的初始数据
     */
    data: {
        nowDate: '',
        goodsId: null,
        belongRefer: null,
        userType: null,
        userInfo: null,
        shopInfo: null,
        goodsInfo: {},
        goodsComment: [],
        goodsMemberPrice: 0,
        goodsMarketPrice: 0,
        goodsFreePrice: 0,
        goodsRoyalty: 0,
        goodsNum: 1,
        commodityAttr: [],
        attrValueList: [],
        formatImg: '',
        nowFormat: '',
        nowFormatSn: '',
        nowFormatId: '',
        showFormat: false,
        showGift: false,
        showShareImg: false,
        animationData1: {},
        goodsIntroList: [],
        previewImg: '',
        userCode: '',
        isSureBuy: false,
        goBuyType: null,
        beVipImg: '',
        tipsImg: '',
        isLoading: false
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        // if (options.storeId) {
        //     wx.setStorageSync('storeId', options.storeId)
        //     if (wx.getStorageSync('token')) {
        //         let data = {
        //             store_id: options.storeId
        //         }
        //         common.post("Store/change_user_store", data).then(function(res) {}).catch(function(e) {})
        //     }
        // }
        if (options.userShare) {
            wx.setStorageSync('userShare', options.userShare)
            let data = {
                belong_refer: options.userShare
            }
            common.post('User/set_belong_refer', data).then(function (res) { }).catch(function (e) { })
        }
        this.setData({
            nowDate: new Date().getTime(),
            goodsId: options.goodsId,
            userType: wx.getStorageSync('roleType')
        })
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        //浏览记录
        if (wx.getStorageSync('token')) {
            let data = {
                client: 2,
                type: 1,
                goods_id: this.data.goodsId
            }
            common.post('Userbrowse/add_goods_click', data).then(function (res) { }).catch(function (e) { })
        }
        this.getBeVipImg()
        this.getTipsImg()
        this.getShopInfo()
        this.getGoodsInfo(this.data.goodsId)
        if (wx.getStorageSync('token')) {
            this.getUserInfo()
        }
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {
        common.refresh()
        setTimeout(function () {
            wx.stopPullDownRefresh()
        }, 2000)
    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function (res) {
        let shareName = this.data.goodsInfo.goods_name.substring(0, 15)
        let shareImg = this.data.goodsInfo.image
        let goodsId = this.data.goodsInfo.goods_id
        let userId = wx.getStorageSync('userId')
        let storeId = wx.getStorageSync('storeId')
        if (userId) {
            return {
                title: shareName,
                path: '/pages/goods/goodsDetail/goodsDetail?goodsId=' + goodsId + '&userShare=' + userId,
                imageUrl: shareImg
            }
        }
    },

    myCatchTouch: function () {
        return
    },

    getShopInfo: function () {
        const that = this
        let data = {
            activity: 785,
            store_id: wx.getStorageSync('storeId') ? wx.getStorageSync('storeId') : 2
        }
        common.post('Store/get_store_info', data).then(function (res) {
            if (res.code == 204) {
                return
            } else {
                that.setData({
                    shopInfo: res
                })
            }
        }).catch(function (e) { })
    },

    getBeVipImg: function () {
        const that = this
        let data = {
            activity: 785,
            images_id: 13
        }
        common.post('Images/get_img', data).then(function (res) {
            that.setData({
                beVipImg: res[0].images
            })
        }).catch(function (e) { })
    },

    getTipsImg: function () {
        const that = this
        let data = {
            activity: 785,
            images_id: 14
        }
        common.post('Images/get_img', data).then(function (res) {
            that.setData({
                tipsImg: res[0].images
            })
        }).catch(function (e) { })
    },

    getUserCode: function () {
        wx.showLoading({
            title: '正在生成图片...',
        })
        const that = this
        let data = {
            store_id: wx.getStorageSync('storeId'),
            goods_id: this.data.goodsInfo.goods_id
        }
        common.post('Qrcodes/app_create_goods_qr', data).then(function (res) {
            that.setData({
                userCode: res
            })
            that.setData({
                showShareImg: true
            })
            that.createImg()
        }).catch(function (e) { })
    },

    createImg: function () {
        const that = this
        const wxGetImageInfo = this.promisify(wx.getImageInfo)
        Promise.all([
            wxGetImageInfo({
                src: 'https://yidianyuan.bailingyoupin.com/static/images/wx_sm/home/shop-goods-share-img.jpg?t=' + that.data.nowDate
            }),
            wxGetImageInfo({
                src: 'https:' + that.data.userInfo.heard_img.split(':')[1]
            }),
            wxGetImageInfo({
                src: 'https:' + that.data.goodsInfo.image.split(':')[1]
            }),
            wxGetImageInfo({
                src: 'https:' + that.data.userCode.split(':')[1]
            })
        ]).then(res => {
            const ctx = wx.createCanvasContext('shareCanvas')
            ctx.drawImage(res[0].path, 0, 0, 750, 1334)
            this.circleImg(ctx, res[1].path, 36, 33, 50)
            ctx.drawImage(res[2].path, 40, 180, 670, 670)
            this.circleImg(ctx, res[3].path, 454, 900, 117)
            ctx.setFillStyle('#131313')
            ctx.setFontSize(30)
            ctx.fillText(that.data.userInfo.nickname + ' 向你推荐', 170, 70)
            ctx.setFillStyle('#000000')
            ctx.setFontSize(26)
            ctx.fillText('邀请码：' + that.data.userInfo.user_id, 170, 115)
            ctx.setFillStyle('#131313')
            ctx.setFontSize(32)
            ctx.fillText(that.data.goodsInfo.goods_name.slice(0, 10) + '...', 40, 1060)
            ctx.setFillStyle('#666666')
            ctx.setFontSize(30)
            ctx.fillText(that.data.goodsInfo.brief.slice(0, 13), 40, 1120)
            if (that.data.goodsInfo.brief.length > 13) {
                ctx.setFillStyle('#666666')
                ctx.setFontSize(30)
                ctx.fillText(that.data.goodsInfo.brief.slice(13, 23) + '...', 40, 1170)
            }
            ctx.font = 'normal bold 47px Biko'
            ctx.setFillStyle('#131313')
            if (that.data.goodsInfo.client == 2) {
                ctx.fillText('￥' + that.data.goodsInfo.price, 40, 955)
            } else {
                ctx.fillText('￥' + that.data.goodsInfo.self_price, 40, 955)
            }
            ctx.draw(false, function (e) {
                wx.hideLoading()
                const wxCanvasToTempFilePath = that.promisify(wx.canvasToTempFilePath)
                wxCanvasToTempFilePath({
                    canvasId: 'shareCanvas',
                    x: 0,
                    y: 0,
                    width: 750,
                    height: 1334
                }, this).then(res => {
                    that.setData({
                        previewImg: res.tempFilePath
                    })
                })
            })
        })
    },

    downloadImg: function () {
        const that = this
        wx.saveImageToPhotosAlbum({
            filePath: this.data.previewImg,
            success: function (data) {
                wx.showToast({
                    title: '保存成功',
                    icon: 'success',
                    duration: 2000
                })
                that.closeShare()
            },
            fail: function (err) {
                if (err.errMsg === "saveImageToPhotosAlbum:fail auth deny") {
                    wx.showModal({
                        title: '用户未授权',
                        content: '请先开启保存到相册权限，开启后即可保存图片',
                        success(res) {
                            if (res.confirm) {
                                wx.openSetting({
                                    success(settingdata) {
                                        if (settingdata.authSetting['scope.writePhotosAlbum']) {
                                            wx.saveImageToPhotosAlbum({
                                                filePath: that.data.previewImg,
                                                success(res) {
                                                    wx.showToast({
                                                        title: '保存成功',
                                                        icon: 'success',
                                                        duration: 2000
                                                    })
                                                    that.closeShare()
                                                }
                                            })
                                        } else {
                                            wx.showToast({
                                                title: '保存图片失败，请确认开启授权后重新保存图片',
                                                icon: 'none',
                                                duration: 2000
                                            })
                                        }
                                    }
                                })
                            } else if (res.cancel) {
                                wx.showToast({
                                    title: '保存图片失败，请确认开启授权后重新保存图片',
                                    icon: 'none',
                                    duration: 2000
                                })
                            }
                        }
                    })
                }
            }
        })
    },

    promisify: function (api) {
        return (options, ...params) => {
            return new Promise((resolve, reject) => {
                const extras = {
                    success: resolve,
                    fail: reject
                }
                api({
                    ...options,
                    ...extras
                }, ...params)
            })
        }
    },

    circleImg: function (ctx, img, x, y, r) {
        ctx.save();
        var d = 2 * r;
        var cx = x + r;
        var cy = y + r;
        ctx.arc(cx, cy, r, 0, 2 * Math.PI);
        ctx.clip();
        ctx.drawImage(img, x, y, d, d);
        ctx.restore();
    },

    getUserInfo: function () {
        const that = this
        let data = {}
        common.post('User/user_info', data).then(function (res) {
            that.setData({
                userInfo: res
            })
        }).catch(function (e) { })
    },

    getGoodsInfo: function (id) {
        wx.showLoading({
            title: '加载中',
        })
        const that = this
        let data
        if (wx.getStorageSync('token')) {
            data = {
                goods_id: id,
                paramter: 1
            }
        }
        else {
            data = {
                activity: 785,
                goods_id: id,
                paramter: 1
            }
        }
        common.post('Goodslist/goods_list', data).then(function (res) {
            if (res[0].agency_again_buy) {
                that.setData({
                    goodsNum: res[0].agency_again_buy.num
                })
            }
            that.setData({
                goodsInfo: res[0],
                goodsMemberPrice: res[0].retail_price,
                goodsMarketPrice: res[0].price,
                goodsFreePrice: res[0].self_price,
                goodsRoyalty: res[0].sku_list[0].royalty,
            })
            that.initFormat()
            that.getIntroList()
            that.getGoodsComment()
        }).catch(function (e) { })
    },

    getGoodsComment: function () {
        const that = this
        let goodsComment = this.data.goodsComment
        let data = {
            activity: 785,
            goods_id: this.data.goodsInfo.goods_id,
            page: 0,
            limit: 5
        }
        common.post('Goodscomment/comment_list', data).then(function (res) {
            if (res.code == 204) {
                that.setData({
                    goodsComment: goodsComment
                })
            } else {
                goodsComment = res
                that.setData({
                    goodsComment: goodsComment
                })
            }
        }).catch(function (e) { })
    },

    getIntroList: function () {
        const that = this
        let data
        if (this.data.goodsInfo.client == 2) {
            data = {
                activity: 785,
                class_id: this.data.goodsInfo.class_id,
                is_goods: 0,
                page: 0,
                limit: 12,
                client: 2
            }
        } else {
            data = {
                activity: 785,
                class_id: this.data.goodsInfo.class_id,
                is_goods: 0,
                page: 0,
                limit: 12,
                client: 1
            }
        }
        common.post('Goodslist/goods_list', data).then(function (res) {
            wx.hideLoading()
            that.setData({
                goodsIntroList: res
            })
        }).catch(function (e) { })
    },

    goBuy: function () {
        if (this.data.nowFormatSn == '' || this.data.nowFormatId == '') {
            if (this.data.showFormat == false) {
                this.showFormatSelect()
            } else {
                wx.showToast({
                    title: '请选择产品规格',
                    icon: 'none',
                    duration: 1000
                })
            }
        } else {
            wx.showLoading({
                title: '加载中',
            })
            let data
            if (this.data.goodsInfo.virtual_goods == 0) {
                if (this.data.userInfo.user_type == 1 || this.data.goodsMemberPrice == 0) {
                    data = {
                        num: this.data.goodsNum,
                        goods_id: this.data.goodsInfo.goods_id,
                        store_id: this.data.goodsInfo.store_id,
                        type: 1,
                        client: 2,
                        sku_sn: this.data.nowFormatSn,
                        sku_id: this.data.nowFormatId
                    }
                } else {
                    data = {
                        num: this.data.goodsNum,
                        goods_id: this.data.goodsInfo.goods_id,
                        store_id: this.data.goodsInfo.store_id,
                        type: 9,
                        client: 2,
                        sku_sn: this.data.nowFormatSn,
                        sku_id: this.data.nowFormatId
                    }
                }
                common.post('Cart/add_cart', data).then(function (res) {
                    wx.hideLoading()
                    wx.switchTab({
                        url: '/pages/cart/cart'
                    })
                }).catch(function (e) { })
            } else {
                if (this.data.userInfo.user_type == 1 || this.data.goodsMemberPrice == 0) {
                    data = {
                        num: this.data.goodsNum,
                        goods_id: this.data.goodsInfo.goods_id,
                        store_id: this.data.goodsInfo.store_id,
                        type: 1,
                        client: 2,
                        sku_sn: this.data.nowFormatSn,
                        sku_id: this.data.nowFormatId
                    }
                } else {
                    data = {
                        num: this.data.goodsNum,
                        goods_id: this.data.goodsInfo.goods_id,
                        store_id: this.data.goodsInfo.store_id,
                        type: 9,
                        client: 2,
                        sku_sn: this.data.nowFormatSn,
                        sku_id: this.data.nowFormatId
                    }
                }
                common.post('Cart/add_cart', data).then(function (res) {
                    wx.hideLoading()
                    let cartSelectList = [{
                        store_id: res.store_id,
                        store_name: res.store_name,
                        goods_sku: [res.goods_sku],
                    }]
                    wx.setStorageSync('actualPrice', res.goods_sku.rel_price * res.num)
                    wx.setStorageSync('servicePrice', 0)
                    wx.setStorageSync('totalPrice', res.goods_sku.rel_price * res.num)
                    wx.setStorageSync('cartIdList', res.cart_id)
                    wx.setStorageSync('cartSelectList', cartSelectList)
                    wx.setStorageSync('isVipGoods', 1)
                    wx.navigateTo({
                        url: '/pages/order/orderConfirm/orderConfirm?type=virtual'
                    })
                }).catch(function (e) { })
            }
        }
    },

    goExclusiveBuy: function () {
        const that = this
        if (this.data.isLoading) {
            return
        }
        if (this.data.nowFormatSn == '' || this.data.nowFormatId == '') {
            if (this.data.showFormat == false) {
                this.showFormatSelect()
            } else {
                wx.showToast({
                    title: '请选择产品规格',
                    icon: 'none',
                    duration: 1000
                })
            }
        } else {
            wx.showLoading({
                title: '加载中',
            })
            this.setData({
                isLoading: true
            })
            let data = {
                num: this.data.goodsNum,
                goods_id: this.data.goodsInfo.goods_id,
                store_id: this.data.goodsInfo.store_id,
                type: 1,
                client: 2,
                sku_sn: this.data.nowFormatSn,
                sku_id: this.data.nowFormatId
            }
            common.post('Cart/add_cart', data).then(function (res) {
                wx.hideLoading()
                wx.login({
                    success(response) {
                        if (response.code) {
                            //发起网络请求
                            let data = {
                                store_id: wx.getStorageSync('storeId'),
                                pay_id: 1,
                                address_id: 1,
                                breft: '',
                                total_price: res.price,
                                pay_client: 1,
                                client: 2,
                                cart_id_list: res.cart_id,
                                is_goods: 8,
                                code: response.code
                            }
                            common.post('Order/new_order', data).then(function (response) {
                                that.setData({
                                    isLoading: false
                                })
                                if (response.code == 204) {
                                    wx.showToast({
                                        title: response.error,
                                        icon: 'none',
                                        duration: 2000
                                    })
                                    return
                                }
                                wx.requestPayment({
                                    timeStamp: response.timeStamp,
                                    nonceStr: response.nonceStr,
                                    package: response.package,
                                    signType: response.signType,
                                    paySign: response.paySign,
                                    success(res) {
                                        wx.navigateTo({
                                            url: '/pages/shopExclusive/orderList/orderList'
                                        })
                                    },
                                    fail(res) {
                                        wx.showToast({
                                            title: '支付失败',
                                            icon: 'none',
                                            duration: 1000
                                        })
                                    }
                                })
                            }).catch(function (e) { })
                        }
                    }
                })
            }).catch(function (e) { })
        }
    },

    goGet: function () {
        if (this.data.nowFormatSn == '' || this.data.nowFormatId == '') {
            if (this.data.showFormat == false) {
                this.showFormatSelect()
            } else {
                wx.showToast({
                    title: '请选择产品规格',
                    icon: 'none',
                    duration: 1000
                })
            }
        } else {
            wx.showLoading({
                title: '加载中',
            })
            let data = {
                num: this.data.goodsNum,
                goods_id: this.data.goodsInfo.goods_id,
                store_id: this.data.goodsInfo.store_id,
                type: 2,
                client: 2,
                sku_sn: this.data.nowFormatSn,
                sku_id: this.data.nowFormatId
            }
            common.post('Cart/add_cart', data).then(function (res) {
                wx.hideLoading()
                wx.switchTab({
                    url: '/pages/cart/cart'
                })
            }).catch(function (e) { })
        }
    },

    beVip: function () {
        if (this.data.nowFormatSn == '' || this.data.nowFormatId == '') {
            if (this.data.showFormat == false) {
                this.showFormatSelect()
            } else {
                wx.showToast({
                    title: '请选择产品规格',
                    icon: 'none',
                    duration: 1000
                })
            }
        } else {
            wx.showLoading({
                title: '加载中',
            })
            const that = this
            if (this.data.goodsInfo.virtual_goods == 1) {
                let data = {
                    num: this.data.goodsNum,
                    goods_id: this.data.goodsInfo.goods_id,
                    store_id: this.data.goodsInfo.store_id,
                    type: 5,
                    client: 2,
                    sku_sn: this.data.nowFormatSn,
                    sku_id: this.data.nowFormatId
                }
                common.post('Cart/add_cart', data).then(function (res) {
                    wx.hideLoading()
                    let cartSelectList = [{
                        store_id: res.store_id,
                        store_name: res.store_name,
                        goods_sku: [res.goods_sku],
                    }]
                    wx.setStorageSync('actualPrice', res.goods_sku.price * res.num)
                    wx.setStorageSync('servicePrice', 0)
                    wx.setStorageSync('totalPrice', res.goods_sku.price * res.num)
                    wx.setStorageSync('cartIdList', res.cart_id)
                    wx.setStorageSync('cartSelectList', cartSelectList)
                    wx.setStorageSync('isVipGoods', 2)
                    wx.navigateTo({
                        url: '/pages/order/orderConfirm/orderConfirm?type=virtual'
                    })
                }).catch(function (e) { })
            } else {
                let data = {
                    num: this.data.goodsNum,
                    goods_id: this.data.goodsInfo.goods_id,
                    store_id: this.data.goodsInfo.store_id,
                    type: 5,
                    client: 2,
                    sku_sn: this.data.nowFormatSn,
                    sku_id: this.data.nowFormatId
                }
                common.post('Cart/add_cart', data).then(function (res) {
                    wx.hideLoading()
                    let cartSelectList = [{
                        store_id: res.store_id,
                        store_name: res.store_name,
                        goods_sku: [res.goods_sku],
                    }]
                    wx.setStorageSync('actualPrice', res.goods_sku.price * res.num)
                    wx.setStorageSync('servicePrice', 0)
                    wx.setStorageSync('totalPrice', res.goods_sku.price * res.num)
                    wx.setStorageSync('cartIdList', res.cart_id)
                    wx.setStorageSync('cartSelectList', cartSelectList)
                    wx.setStorageSync('isVipGoods', 2)
                    wx.navigateTo({
                        url: '/pages/order/orderConfirm/orderConfirm'
                    })
                }).catch(function (e) { })
            }
        }
    },

    agentGoodsBuy: function () {
        if (this.data.nowFormatSn == '' || this.data.nowFormatId == '') {
            if (this.data.showFormat == false) {
                this.showFormatSelect()
            } else {
                wx.showToast({
                    title: '请选择产品规格',
                    icon: 'none',
                    duration: 1000
                })
            }
            return
        }
        wx.showLoading({
            title: '请稍后'
        })
        const that = this
        let data = {
            num: this.data.goodsNum,
            goods_id: this.data.goodsInfo.goods_id,
            store_id: this.data.goodsInfo.store_id,
            type: 5,
            client: 2,
            sku_sn: this.data.nowFormatSn,
            sku_id: this.data.nowFormatId
        }
        common.post('Cart/add_cart', data).then(function (res) {
            wx.hideLoading()
            let cartSelectList = [{
                store_id: res.store_id,
                store_name: res.store_name,
                goods_sku: [res.goods_sku],
            }]
            wx.setStorageSync('actualPrice', res.goods_sku.price * res.num)
            wx.setStorageSync('servicePrice', 0)
            wx.setStorageSync('totalPrice', res.goods_sku.price * res.num)
            wx.setStorageSync('cartIdList', res.cart_id)
            wx.setStorageSync('cartSelectList', cartSelectList)
            wx.setStorageSync('isVipGoods', 2)
            wx.navigateTo({
                url: '/pages/order/orderConfirm/orderConfirm?type=agent'
            })
        }).catch(function (e) { })
    },

    showFormatSelect: function () {
        var animation = wx.createAnimation({
            duration: 500,
            timingFunction: "ease",
            delay: 0
        })
        this.animation = animation
        animation.translateY(1500).step()
        this.setData({
            animationData: animation.export(), // export 方法每次调用后会清掉之前的动画操作。
            showFormat: true
        })
        setTimeout(() => {
            animation.translateY(0).step()
            this.setData({
                animationData: animation.export() // export 方法每次调用后会清掉之前的动画操作。
            })
        }, 200)
    },

    closeFormatSelect: function () {
        var animation = wx.createAnimation({
            duration: 500,
            timingFunction: "ease",
            delay: 0
        })
        this.animation = animation
        animation.translateY(1500).step()
        this.setData({
            animationData: animation.export(),
        })
        setTimeout(function () {
            animation.translateY(0).step()
            this.setData({
                animationData: animation.export(),
                showFormat: false,
                isSureBuy: false
            })
        }.bind(this), 200)
    },

    showGiftSelect: function () {
        var animation = wx.createAnimation({
            duration: 500,
            timingFunction: "ease",
            delay: 0
        })
        this.animation = animation
        animation.translateY(1500).step()
        this.setData({
            animationData: animation.export(), // export 方法每次调用后会清掉之前的动画操作。
            showGift: true
        })
        setTimeout(() => {
            animation.translateY(0).step()
            this.setData({
                animationData: animation.export() // export 方法每次调用后会清掉之前的动画操作。
            })
        }, 200)
    },

    closeGiftSelect: function () {
        var animation = wx.createAnimation({
            duration: 500,
            timingFunction: "ease",
            delay: 0
        })
        this.animation = animation
        animation.translateY(1500).step()
        this.setData({
            animationData: animation.export(),
        })
        setTimeout(function () {
            animation.translateY(0).step()
            this.setData({
                animationData: animation.export(),
                showGift: false
            })
        }.bind(this), 200)
    },

    share: function () {
        this.getUserCode()
    },

    closeShare: function () {
        this.setData({
            showShareImg: false
        })
    },

    goodsNumAdd: function () {
        let goodsNum = this.data.goodsNum
        if (this.data.goodsInfo.is_goods == 0 || this.data.goodsInfo.agency_goods == 1) {
            goodsNum++
        }
        this.setData({
            goodsNum: goodsNum
        })
    },

    goodsNumMinus: function () {
        let goodsNum = this.data.goodsNum
        if (goodsNum > 1) {
            if (this.data.userInfo.store_type > 0) {
                if (goodsNum > this.data.goodsInfo.agency_again_buy.num) {
                    goodsNum--
                    this.setData({
                        goodsNum: goodsNum
                    })
                }
                else {
                    return
                }
            }
            else {
                goodsNum--
                this.setData({
                    goodsNum: goodsNum
                })
            }
        }
    },

    initFormat: function () {

        this.setData({
            commodityAttr: this.data.goodsInfo.sku_list
        })
        this.setData({
            formatImg: this.data.goodsInfo.image_thumb,
            goodsMemberPrice: this.data.goodsInfo.retail_price,
            goodsMarketPrice: this.data.goodsInfo.price,
            goodsFreePrice: this.data.goodsInfo.self_price,
            goodsRoyalty: this.data.goodsInfo.sku_list[0].royalty,
            includeGroup: this.data.commodityAttr
        });

        this.distachAttrValue(this.data.commodityAttr);
        // 只有一个属性组合的时候默认选中 
        if (this.data.commodityAttr.length == 1) {
            for (var i = 0; i < this.data.commodityAttr[0].attrValueList.length; i++) {
                this.data.attrValueList[i].selectedValue = this.data.commodityAttr[0].attrValueList[i].attrValue;
            }
            let nowFormat = ''
            this.data.includeGroup[0].attrValueList.forEach(function (e) {
                nowFormat += e.attrValue + '，'
            })
            this.setData({
                attrValueList: this.data.attrValueList,
                goodsMemberPrice: this.data.includeGroup[0].retail_price,
                goodsMarketPrice: this.data.includeGroup[0].price,
                goodsFreePrice: this.data.includeGroup[0].self_price,
                goodsRoyalty: this.data.includeGroup[0].royalty,
                formatImg: this.data.includeGroup[0].img,
                nowFormat: nowFormat,
                nowFormatSn: this.data.includeGroup[0].sku_sn,
                nowFormatId: this.data.includeGroup[0].sku_id
            });
        }

    },
    /* 获取数据 */
    distachAttrValue: function (commodityAttr) {

        /** 
        将后台返回的数据组合成类似 
        { 
        attrKey:'型号', 
        attrValueList:['1','2','3'] 
        } 
        */
        // 把数据对象的数据（视图使用），写到局部内 
        var attrValueList = this.data.attrValueList;
        // 遍历获取的数据 
        for (var i = 0; i < commodityAttr.length; i++) {

            for (var j = 0; j < commodityAttr[i].attrValueList.length; j++) {
                var attrIndex = this.getAttrIndex(commodityAttr[i].attrValueList[j].attrKey, attrValueList);
                // 如果还没有属性索引为-1，此时新增属性并设置属性值数组的第一个值；索引大于等于0，表示已存在的属性名的位置 
                if (attrIndex >= 0) {
                    // 如果属性值数组中没有该值，push新值；否则不处理 
                    if (!this.isValueExist(commodityAttr[i].attrValueList[j].attrValue, attrValueList[attrIndex].attrValues)) {
                        attrValueList[attrIndex].attrValues.push(commodityAttr[i].attrValueList[j].attrValue);
                    }
                } else {
                    attrValueList.push({
                        attrKey: commodityAttr[i].attrValueList[j].attrKey,
                        attrValues: [commodityAttr[i].attrValueList[j].attrValue]
                    });
                }
            }
        }

        // console.log('result', attrValueList) 
        for (var i = 0; i < attrValueList.length; i++) {
            for (var j = 0; j < attrValueList[i].attrValues.length; j++) {
                if (attrValueList[i].attrValueStatus) {
                    attrValueList[i].attrValueStatus[j] = true;
                } else {
                    attrValueList[i].attrValueStatus = [];
                    attrValueList[i].attrValueStatus[j] = true;
                }
            }
        }
        this.setData({
            attrValueList: attrValueList
        });
    },
    getAttrIndex: function (attrName, attrValueList) {
        // 判断数组中的attrKey是否有该属性值 
        for (var i = 0; i < attrValueList.length; i++) {
            if (attrName == attrValueList[i].attrKey) {
                break;
            }
        }
        return i < attrValueList.length ? i : -1;
    },
    isValueExist: function (value, valueArr) {
        // 判断是否已有属性值 
        for (var i = 0; i < valueArr.length; i++) {
            if (valueArr[i] == value) {
                break;
            }
        }
        return i < valueArr.length;
    },
    /* 选择属性值事件 */
    selectAttrValue: function (e) {
        /* 
        点选属性值，联动判断其他属性值是否可选 
        { 
        attrKey:'型号', 
        attrValueList:['1','2','3'], 
        selectedValue:'1', 
        attrValueStatus:[true,true,true] 
        } 
        console.log(e.detail.currentTarget.dataset); 
        */
        var attrValueList = this.data.attrValueList;
        var index = e.currentTarget.dataset.index; //属性索引 
        var key = e.currentTarget.dataset.key;
        var value = e.currentTarget.dataset.value;
        if (e.currentTarget.dataset.status || index == this.data.firstIndex) {
            if (e.currentTarget.dataset.selectedvalue == e.currentTarget.dataset.value) {
                // 取消选中 
                this.disSelectValue(attrValueList, index, key, value);
            } else {
                // 选中 
                this.selectValue(attrValueList, index, key, value);
            }

        }
    },
    /* 选中 */
    selectValue: function (attrValueList, index, key, value, unselectStatus) {
        const that = this
        // console.log('firstIndex', this.data.firstIndex); 
        var includeGroup = [];
        if (index == this.data.firstIndex && !unselectStatus) { // 如果是第一个选中的属性值，则该属性所有值可选 
            var commodityAttr = this.data.commodityAttr;
            // 其他选中的属性值全都置空 
            // console.log('其他选中的属性值全都置空', index, this.data.firstIndex, !unselectStatus); 
            for (var i = 0; i < attrValueList.length; i++) {
                for (var j = 0; j < attrValueList[i].attrValues.length; j++) {
                    attrValueList[i].selectedValue = '';
                }
            }
        } else {
            var commodityAttr = this.data.includeGroup;
        }

        // console.log('选中', commodityAttr, index, key, value); 
        for (var i = 0; i < commodityAttr.length; i++) {
            for (var j = 0; j < commodityAttr[i].attrValueList.length; j++) {
                if (commodityAttr[i].attrValueList[j].attrKey == key && commodityAttr[i].attrValueList[j].attrValue == value) {
                    includeGroup.push(commodityAttr[i]);
                }
            }
        }
        attrValueList[index].selectedValue = value;

        // 判断属性是否可选 
        for (var i = 0; i < attrValueList.length; i++) {
            for (var j = 0; j < attrValueList[i].attrValues.length; j++) {
                attrValueList[i].attrValueStatus[j] = false;
            }
        }
        for (var k = 0; k < attrValueList.length; k++) {
            for (var i = 0; i < includeGroup.length; i++) {
                for (var j = 0; j < includeGroup[i].attrValueList.length; j++) {
                    if (attrValueList[k].attrKey == includeGroup[i].attrValueList[j].attrKey) {
                        for (var m = 0; m < attrValueList[k].attrValues.length; m++) {
                            if (attrValueList[k].attrValues[m] == includeGroup[i].attrValueList[j].attrValue) {
                                attrValueList[k].attrValueStatus[m] = true;
                            }
                        }
                    }
                }
            }
        }
        // console.log('结果', attrValueList); 
        this.setData({
            attrValueList: attrValueList,
            includeGroup: includeGroup
        });

        let nowFormat = ''
        includeGroup[0].attrValueList.forEach(function (e) {
            nowFormat += e.attrValue + '，'
        })
        var count = 0;
        for (var i = 0; i < attrValueList.length; i++) {
            for (var j = 0; j < attrValueList[i].attrValues.length; j++) {
                if (attrValueList[i].selectedValue) {
                    count++;
                    if (count == attrValueList.length) {
                        that.setData({
                            goodsMemberPrice: includeGroup[0].retail_price,
                            goodsMarketPrice: includeGroup[0].price,
                            goodsFreePrice: includeGroup[0].self_price,
                            goodsRoyalty: includeGroup[0].royalty,
                            formatImg: includeGroup[0].img,
                            nowFormat: nowFormat,
                            nowFormatSn: includeGroup[0].sku_sn,
                            nowFormatId: includeGroup[0].sku_id
                        })
                    }
                    break;
                }
            }
        }

        if (count < 2) { // 第一次选中，同属性的值都可选 
            this.setData({
                firstIndex: index
            });
        } else {
            this.setData({
                firstIndex: -1
            });
        }
    },
    /* 取消选中 */
    disSelectValue: function (attrValueList, index, key, value) {
        var commodityAttr = this.data.commodityAttr;
        attrValueList[index].selectedValue = '';

        // 判断属性是否可选 
        for (var i = 0; i < attrValueList.length; i++) {
            for (var j = 0; j < attrValueList[i].attrValues.length; j++) {
                attrValueList[i].attrValueStatus[j] = true;
            }
        }
        this.setData({
            includeGroup: commodityAttr,
            attrValueList: attrValueList
        });

        for (var i = 0; i < attrValueList.length; i++) {
            if (attrValueList[i].selectedValue) {
                this.selectValue(attrValueList, i, attrValueList[i].attrKey, attrValueList[i].selectedValue, true);
            }
        }

        this.setData({
            goodsMemberPrice: this.data.goodsInfo.retail_price,
            goodsMarketPrice: this.data.goodsInfo.price,
            goodsFreePrice: this.data.goodsInfo.self_price,
            goodsRoyalty: this.data.goodsInfo.sku_list[0].royalty,
            formatImg: this.data.goodsInfo.image_thumb,
            nowFormat: '',
            nowFormatSn: '',
            nowFormatId: ''
        })
    },
    previewImg: function (e) {
        let goodsImg = this.data.goodsInfo.vice_big;
        goodsImg.unshift(this.data.goodsInfo.image)
        wx.previewImage({
            current: e.detail, // 当前显示图片的http链接
            urls: goodsImg // 需要预览的图片http链接列表
        })
    }
})